package cn.itlaobing.web.LoginFilter;

import cn.itlaobing.model.UserModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by lhb on 2017/11/3.
 */
@WebFilter("/*")
public class LoginFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=null;
        HttpServletResponse rep=null;
        if(request instanceof HttpServletRequest){
            req=(HttpServletRequest)request;
        }

        if(response instanceof HttpServletResponse){
            rep=(HttpServletResponse)response;
        }
        req.setCharacterEncoding("UTF-8");//设置字符集
        //取得当前请求的地址
        String requestUrl=req.getRequestURI();
        if("/login.jsp".equals(requestUrl) || "/user/login".equals(requestUrl)){
            chain.doFilter(req,rep);//放行
        }else{
            //判断是否登录
            if(req.getSession().getAttribute("USER")==null){
                //跳转到登陆页面
                req.getSession().setAttribute("msg","请登录后再操作！");
                rep.sendRedirect(req.getContextPath()+"/login.jsp");
                return;
            }else{
                //如果登录，则放行
                chain.doFilter(req,rep);//放行
            }
        }
    }
    @Override
    public void destroy() {

    }
}
